package com.itheima.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.itheima.common.CustomException;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;


import java.util.*;

@Log4j2
@Component
public class JwtUtil {
    //鉴权 相当于私钥保存在服务器上
    private static final String secret = "longbosheng";

    /**
     * 管理员生成token
     *
     * @param
     * @return
     */
    public static String getToken(String id, String username) {
        System.out.println("id:"+id);
        //默认七天过期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 5);
        //创建JWT
        JWTCreator.Builder builder = JWT.create();
        //payload
        builder.withClaim("id", id);
        builder.withClaim("username", username);
        //指定令牌过期时间
        builder.withExpiresAt(instance.getTime());
        String token = builder.sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     * 用户生成token
     * @param id
     * @param phone
     * @return
     */
    public static String getToken2(String id, String phone) {
        System.out.println("id:"+id);
        //默认七天过期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 5);
        //创建JWT
        JWTCreator.Builder builder = JWT.create();
        //payload
        builder.withClaim("id", id);
        builder.withClaim("phone", phone);
        //指定令牌过期时间
        builder.withExpiresAt(instance.getTime());
        String token = builder.sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        try {
            return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            log.error("无效签名！");
            throw new CustomException("无效签名！");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            log.error("token过期");
            throw new CustomException("token过期");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            log.error("算法不一致");
            throw new CustomException("算法不一致");
        //登录时生成token
        } catch (Exception e) {
            e.printStackTrace();
            log.error("token无效！");
            throw new CustomException("token无效！");
        }

    }
}